package com.bw.controller.customer;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.customer.PiCustomer;
import com.bw.entity.linkman.PiLinkman;
import com.bw.resp.ResponseResult;
import com.bw.service.customer.IPiCustomerService;
import com.bw.service.linkman.IPiLinkmanService;
import com.bw.utils.excel.ImportExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fankai
 * @since 2020-06-16
 */
@CrossOrigin
@RestController
@RequestMapping("/customer")
public class PiCustomerController {

    @Autowired
    private IPiCustomerService iPiCustomerService;

    @Autowired
    private IPiLinkmanService linkmanService;

    /**
     * 客户列表
     * @param piCustomer
     * @param currentPage
     * @param pageSize
     * @return
     */
    @PostMapping("/list/{pagenum}/{pagesize}")
    public ResponseResult CustomerList(@RequestBody PiCustomer piCustomer, @PathVariable("pagenum")Integer currentPage, @PathVariable("pagesize")Integer pageSize){
        ResponseResult responseResult=ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper=new QueryWrapper();
            PageHelper.startPage(currentPage,pageSize);
            if (piCustomer.getName()!=null){
                queryWrapper.like("name",piCustomer.getName());
            }
            queryWrapper.eq("isDel",0);
            List list = iPiCustomerService.list(queryWrapper);
            PageInfo pageInfo=new PageInfo(list);
            responseResult.setMessage("查询成功");
            responseResult.setResult(pageInfo);
        } catch (Exception e) {
          responseResult.setMessage("查询失败"+e.toString());
            responseResult.setResult(false);
        }
        return responseResult;
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @GetMapping("/details/{id}")
    public ResponseResult Details(@PathVariable("id")Long id){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("id",id);
            List<PiCustomer> customers = iPiCustomerService.list(queryWrapper);
            PiCustomer piCustomer=customers.get(0);
            result.setResult(piCustomer);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("查询失败！"+e.toString());
        }
        return result;
    }

    /**
     * 保存/修改
     * @param piCustomer
     * @return
     */
    @PostMapping("saveCustomer")
    public ResponseResult SaveCustomer(@RequestBody PiCustomer piCustomer){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper=new QueryWrapper();
            int num=(int) (((Math.random()+1)*10)*100000);
            String h="bh";
            piCustomer.setCode(h+num);
            piCustomer.setIsDel(0);
            iPiCustomerService.saveOrUpdate(piCustomer);
            result.setSuccess(true);
            result.setMessage("保存成功");
        } catch (Exception e) {
           result.setSuccess(false);
           result.setMessage("保存失败");
        }
        return result;
    }

    /**
     * 逻辑删除
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    public ResponseResult del(@PathVariable Long id){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            PiCustomer customer = iPiCustomerService.getById(id);
            customer.setIsDel(1);
            iPiCustomerService.saveOrUpdate(customer);
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("isDel",0);
            List list = iPiCustomerService.list(queryWrapper);
            result.setResult(list);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("删除失败"+toString());
        }
        return result;

    }

    /**
     * 判断编号的唯一性
     * @param code
     * @return
     */
    @GetMapping("/hasCode/{code}")
    public ResponseResult hasCode(@PathVariable("code")String code){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("code",code);
            List list = iPiCustomerService.list(queryWrapper);
            if (list.size()>0){
                result.setSuccess(false);
                result.setMessage("该编号已经存在！！");
            }else {
                result.setSuccess(true);
                result.setMessage("ok!");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("查询编号失败"+e.toString());
        }
        return result;
    }


   /* *//**
     * 导出
     * @param response
     * @throws Exception
     *//*
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        List<PiCustomer> userList=iPiCustomerService.list();//获取用户列表数据
        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");//导出的文本格式
        //设置名称
        response.setHeader("Content-Disposition","attachment;filename="+new String("用户数据".getBytes(),"iso-8859-1")+".xls");

        //excel模板的流获取
        ClassPathResource classPathResource=new ClassPathResource("xls/user.xls");//定位位置
        InputStream inputStream=classPathResource.getInputStream();//获取excel模板的输入流
        ExcelUtils.addValue("list",userList);

        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());//第一个参数是模板流
    }*/

    /**
     * excel上传
     */
    /*@PostMapping("importExcel")
    public ResponseResult importExcel(MultipartFile file) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //1，获取文件后缀
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            List<Map> mapList= ExcelUtil.readExcel(ext,file.getInputStream());

            String jsonStr = JSON.toJSONString(mapList);//map集合转换成json字符串

               List<PiCustomer> piCustomers=JSON.parseArray(jsonStr,PiCustomer.class);//json转换成list集合
               iPiCustomerService.saveBatch(piCustomers);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("解析失败:" + e.toString());
        }
        return result;
    }*/


    /**
     * 导入excel文件
     */
    @PostMapping("importExcel")
    public ResponseResult importExcel(MultipartFile file){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //获取文件的后缀名
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            //利用工具类进行输出
            InputStream inputStream = file.getInputStream();

            List<Map> list = ImportExcel.readExcel(ext, inputStream);

            String string = JSON.toJSONString(list);

            List<PiCustomer> customerList = JSON.parseArray(string, PiCustomer.class);

            for (int i=0;i<customerList.size();i++){
                int num=(int) (((Math.random()+1)*10)*100000);
                String h="bh"+num;
                customerList.get(i).setCode(h);
                customerList.get(i).setIsDel(0);
            }

            iPiCustomerService.saveBatch(customerList);

        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("导入失败!"+e.toString());
        }
        return result;
    }

    @GetMapping("exportExcel")
    public void exportExcel(HttpServletResponse response){
        try {
            //从数据库获取数据
            List<PiCustomer> customerList = iPiCustomerService.list();
            //创建路径数据源路径
            ClassPathResource classPathResource = new ClassPathResource("xls/customer.xls");
            //将文件添加到输入刘中
            InputStream inputStream = classPathResource.getInputStream();
            //利用工具类添加数据到
            ExcelUtils.addValue("list",customerList);

            //第一个参数是模板流

            response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition","attachment;filename="+new String("客户数据".getBytes(),"iso-8859-1")+".xlsx");

            ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());
        }catch (Exception e){
            e.toString();
        }

    }

    /**
     * 查看联系人
     * @param id
     * @return
     */
    @GetMapping("/toLinken/{id}")
    public ResponseResult toLinken(@PathVariable("id")Long id){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("customerId",id);
            List<PiLinkman> list = linkmanService.list(queryWrapper);
            result.setResult(list);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败！"+e.toString());
        }
        return result;
    }


}
